package com.ruoyi.zxjd.exposure.controller;

import java.util.*;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.SmsUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.zxjd.common.CommonConstants;
import com.ruoyi.zxjd.common.domain.CommonUserVO;
import com.ruoyi.zxjd.common.mapper.CommonMapper;
import com.ruoyi.zxjd.conference.domain.ConferenceArrange;
import com.ruoyi.zxjd.exposure.domain.ExposureProgress;
import com.ruoyi.zxjd.work.domain.WorkHandle;
import com.ruoyi.zxjd.work.service.IWorkHandleService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.zxjd.exposure.domain.ExposureArrange;
import com.ruoyi.zxjd.exposure.service.IExposureArrangeService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

import javax.annotation.Resource;
import javax.validation.constraints.Size;

/**
 * 曝光台列表Controller
 * 
 * @author lcc
 * @date 2021-02-07
 */
@Controller
@RequestMapping("/exposure/arrange")
public class ExposureArrangeController extends BaseController
{
    private String prefix = "exposure/arrange";

    @Autowired
    private IExposureArrangeService exposureArrangeService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private IWorkHandleService workHandleService;

    @Resource
    private CommonMapper commonMapper;

    @RequiresPermissions("exposure:arrange:view")
    @GetMapping()
    public String arrange()
    {
        return prefix + "/arrange";
    }

    /**
     * 查询曝光台列表列表
     */
    @RequiresPermissions("exposure:arrange:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(ExposureArrange exposureArrange)
    {
        startPage();
        List<ExposureArrange> list = exposureArrangeService.selectExposureArrangeList(exposureArrange);
        return getDataTable(list);
    }

    /**
     * 导出曝光台列表列表
     */
    @RequiresPermissions("exposure:arrange:export")
    @Log(title = "曝光台列表", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(ExposureArrange exposureArrange)
    {
        List<ExposureArrange> list = exposureArrangeService.selectExposureArrangeList(exposureArrange);
        ExcelUtil<ExposureArrange> util = new ExcelUtil<ExposureArrange>(ExposureArrange.class);
        return util.exportExcel(list, "arrange");
    }

    /**
     * 新增曝光台列表
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存曝光台列表
     */
    @RequiresPermissions("exposure:arrange:add")
    @Log(title = "曝光台列表", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(ExposureArrange exposureArrange)
    {
        //默认为草稿
        exposureArrange.setStatus("0");
        return toAjax(exposureArrangeService.insertExposureArrange(exposureArrange));
    }

    /**
     * 新增保存（发布）曝光台列表
     */
    @RequiresPermissions("exposure:arrange:add")
    @Log(title = "曝光台列表", businessType = BusinessType.INSERT)
    @PostMapping("/add1")
    @ResponseBody
    @Transactional
    public AjaxResult addSave1(ExposureArrange exposureArrange)
    {
        //默认为草稿
        exposureArrange.setStatus("0");
        exposureArrangeService.insertExposureArrange(exposureArrange);
        //立即曝光
        return toAjax(exposureArrangeService.updateStatusByArrangeId(exposureArrange.getArrangeId(), CommonConstants.DRAFT));
    }

    /**
     * 修改曝光台列表
     */
    @GetMapping("/edit/{arrangeId}")
    public String edit(@PathVariable("arrangeId") Long arrangeId, ModelMap mmap)
    {
        ExposureArrange exposureArrange = exposureArrangeService.selectExposureArrangeById(arrangeId);
        mmap.put("exposureArrange", exposureArrange);
        return prefix + "/edit";
    }

    /**
     * 修改保存曝光台列表
     */
    @RequiresPermissions("exposure:arrange:edit")
    @Log(title = "曝光台列表", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(ExposureArrange exposureArrange)
    {
        //默认为草稿
        exposureArrange.setStatus("0");
        //old曝光
        ExposureArrange exposureArrange1 = exposureArrangeService.selectExposureArrangeById(exposureArrange.getArrangeId());
        //曝光题目
        String arrangeTitle = exposureArrange1.getArrangeTitle();
        //曝光发起部门
        String deptName = exposureArrange1.getDeptName();

        String releaseScope = exposureArrange1.getReleaseScope();
        String[] ids = new String[0];
        String[] userNames = releaseScope.split(" ");
        for (int i=0;i<userNames.length;i++){
            SysUser sysUser = sysUserService.selectUserByName(userNames[i]);
            ids = Arrays.copyOf(ids, ids.length + 1); // 数组增加一个长度
            ids[ids.length - 1] = sysUser.getUserId()+""; // 在增加的位置赋值需要添加的数据
        }
        exposureArrange1.setUserIds(ids);
        String[] userIds = exposureArrange1.getUserIds();
        List<CommonUserVO> list = null;

        if(CommonConstants.AllUSER.equals(releaseScope)){
            list = commonMapper.listActiveUser(null,null);
        }else{
            list = commonMapper.listActiveUserByIds(userIds);
        }
        if(StringUtils.isNotNull(list)) {
            if (StringUtils.equals(CommonConstants.PUBLISHED, exposureArrange1.getStatus())) {
                //短信提示
                if (StringUtils.equals(CommonConstants.TIPS, exposureArrange1.getSmsTips())) {
                    AsyncManager.me().execute(createSmsTips(exposureArrange1.getArrangeTitle(), list,exposureArrange1));
                }
                //平台提示
                if (StringUtils.equals(CommonConstants.TIPS, exposureArrange1.getWebsiteTips())) {
                    AsyncManager.me().execute(createWebsiteTips(list, 1));
                }
            }
        }

        return toAjax(exposureArrangeService.updateExposureArrange(exposureArrange));
    }

    /**
     * 修改保存（发布）曝光台列表
     */
    @RequiresPermissions("exposure:arrange:edit")
    @Log(title = "曝光台列表", businessType = BusinessType.UPDATE)
    @PostMapping("/edit1")
    @ResponseBody
    public AjaxResult editSave1(ExposureArrange exposureArrange)
    {
        //默认为草稿
        exposureArrange.setStatus("0");
        //old曝光
        ExposureArrange exposureArrange1 = exposureArrangeService.selectExposureArrangeById(exposureArrange.getArrangeId());
        //曝光题目
        String arrangeTitle = exposureArrange1.getArrangeTitle();
        //曝光发起部门
        String deptName = exposureArrange1.getDeptName();

        String releaseScope = exposureArrange1.getReleaseScope();
        String[] ids = new String[0];
        String[] userNames = releaseScope.split(" ");
        for (int i=0;i<userNames.length;i++){
            SysUser sysUser = sysUserService.selectUserByName(userNames[i]);
            ids = Arrays.copyOf(ids, ids.length + 1); // 数组增加一个长度
            ids[ids.length - 1] = sysUser.getUserId()+""; // 在增加的位置赋值需要添加的数据
        }
        exposureArrange1.setUserIds(ids);
        String[] userIds = exposureArrange1.getUserIds();
        List<CommonUserVO> list = null;

        if(CommonConstants.AllUSER.equals(releaseScope)){
            list = commonMapper.listActiveUser(null,null);
        }else{
            list = commonMapper.listActiveUserByIds(userIds);
        }
        if(StringUtils.isNotNull(list)) {
            if (StringUtils.equals(CommonConstants.PUBLISHED, exposureArrange1.getStatus())) {
                //短信提示
                if (StringUtils.equals(CommonConstants.TIPS, exposureArrange1.getSmsTips())) {
                    AsyncManager.me().execute(createSmsTips(exposureArrange1.getArrangeTitle(), list,exposureArrange1));
                }
                //平台提示
                if (StringUtils.equals(CommonConstants.TIPS, exposureArrange1.getWebsiteTips())) {
                    AsyncManager.me().execute(createWebsiteTips(list, 1));
                }
            }
        }
        exposureArrangeService.updateExposureArrange(exposureArrange);
        //立即曝光
        return toAjax(exposureArrangeService.updateStatusByArrangeId(exposureArrange.getArrangeId(), CommonConstants.DRAFT));
    }

    /**
     * 删除曝光台列表
     */
    @RequiresPermissions("exposure:arrange:remove")
    @Log(title = "曝光台列表", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(exposureArrangeService.deleteExposureArrangeByIds(ids));
    }

    /**
     * 发布曝光
     */
    //@RequiresPermissions("conference:arrange:release")
    @Log(title = "发布曝光", businessType = BusinessType.UPDATE)
    @PostMapping("/release")
    @ResponseBody
    @Transactional
    public AjaxResult release(Long arrangeId)
    {
        return toAjax(exposureArrangeService.updateStatusByArrangeId(arrangeId, CommonConstants.DRAFT));
    }

    /**
     * 撤销工作
     */
    //@RequiresPermissions("conference:arrange:withdraw")
    @Log(title = "撤销曝光", businessType = BusinessType.UPDATE)
    @PostMapping("/withdraw")
    @ResponseBody
    @Transactional
    public AjaxResult withdraw(Long arrangeId)
    {
        ExposureArrange exposureArrange = exposureArrangeService.selectExposureArrangeById(arrangeId);
        //曝光主题
        String arrangeTitle = exposureArrange.getArrangeTitle();

        String releaseScope = exposureArrange.getReleaseScope();
        if ("1".equals(exposureArrange.getSmsTips())){
            String[] userNames = releaseScope.split(" ");
            for (int i=0;i<userNames.length;i++) {
                String userName=userNames[i];
                SysUser sysUser = sysUserService.selectUserByName(userName);
                //发送对象的手机号
                @Size(min = 0, max = 11, message = "手机号码长度不能超过11个字符") String phonenumber = sysUser.getPhonenumber();
                String sms=userName+":您好！在线监督平台提示:关于"+arrangeTitle+"的曝光已被取消";
                SmsUtil.sendMessage(sms,phonenumber);
            }
        }
        return toAjax(exposureArrangeService.updateStatusByArrangeId(arrangeId, CommonConstants.ENABLE));
    }

    private TimerTask createSmsTips(String arrangeTitle, List<CommonUserVO> list, ExposureArrange exposureArrange) {
        return new TimerTask()
        {
            @Override
            public void run()
            {
                for (CommonUserVO commonUserVO : list) {
                    String message = commonUserVO.getUserName()+"，您好！在线监督平台提示:关于"+arrangeTitle+"的曝光已更改，具体事宜请注意后续通知！";
                    String mobileNo = commonUserVO.getPhonenumber();
                    if(StringUtils.isNotEmpty(mobileNo)){
                        SmsUtil.sendMessage(message, mobileNo);
                    }
                }
            }
        };
    }

    private TimerTask createWebsiteTips(List<CommonUserVO> list, int num) {
        return new TimerTask()
        {
            @Override
            public void run()
            {
                for (CommonUserVO commonUserVO : list) {
                    WorkHandle workHandle = new WorkHandle();
                    workHandle.setUserId(commonUserVO.getUserId());
                    workHandle.setType(CommonConstants.WORK);
                    workHandleService.insertOrUpdateWorkHandle(workHandle, num); //工作项+1
                }
            }
        };
    }
}
